﻿#define _CRT_SECURE_NO_WARNINGS
#include"game.h"
void menu()
{
    printf("***********************\n");
    printf("***** 1. play     *****\n");
    printf("***** 0. exit     *****\n");
    printf("***********************\n");
}

void game()
{
    char mine[ROWS][COLS];    //存放布置好的雷
    char show[ROWS][COLS];    //存放排查出的雷的信息

    InitBoard(mine, ROWS, COLS, '0');     //mine数组最开始是全'0'

    InitBoard(show, ROWS, COLS, '*');     //show数组最开始是全'*'

    DisplayBoard(show, ROW, COL);         //打印棋盘

    SetMine(mine, ROW, COL);     // 布置雷

    FindMine(mine, show, ROW, COL);     //布置雷
}
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)//初始化11*11的棋盘
{
    int i = 0;
    for (i = 0; i < rows; i++)
    {
        int j = 0;
        for (j = 0; j < cols; j++)
        {
            board[i][j] = set;
        }
    }
}

void DisplayBoard(char board[ROWS][COLS], int row, int col)//显示玩家看见的9*9的棋盘
{
    int i = 0;
    printf("--------扫雷游戏-------\n");
    for (i = 0; i <= col; i++)
    {
        printf("%d ", i);
    }
    printf("\n");

    for (i = 1; i <= row; i++)
    {
        printf("%d ", i);
        int j = 0;
        for (j = 1; j <= col; j++)
        {
            printf("%c ", board[i][j]);
        }
        printf("\n");
    }
}

void SetMine(char board[ROWS][COLS], int row, int col) //布置10个雷
{

    int count = EASY_COUNT;
    while (count)
    {
        int x = rand() % row + 1;    //使x范围为1~9
        int y = rand() % col + 1;    //使y范围为1~9
        if (board[x][y] == '0')      //布置时可能重复布置，使用if（）在未布置雷处布置雷
        {
            board[x][y] = '1';
            count--;
        }
    }
}

int GetMineCount(char mine[ROWS][COLS], int x, int y)
{
    {
        return (mine[x - 1][y] + mine[x - 1][y - 1] + mine[x - 1][y + 1] +  mine[x][y-1]+mine[x][y+1] + mine[x + 1][y] + mine[x+1][y-1] + mine[x + 1][y + 1] - 8 * '0');
    }
}

void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
    int x = 0;
    int y = 0;
    int win = 0;
    while (win < row * col - EASY_COUNT)                    //当win小于非0坐标个数时继续排雷
    {
        printf("请输入要排查的坐标:>");
        scanf("%d %d", &x, &y);
        if (x >= 1 && x <= row && y >= 1 && y <= col)
        {
            if (mine[x][y] == '1')
            {
                printf("很遗憾，你被炸死了\n\n");            //踩雷失败，打印雷所在位置
                DisplayBoard(mine, ROW, COL);
                break;
            }

            else
            {
                int count = GetMineCount(mine, x, y);    //展示这个位置附近有几个雷
                show[x][y] = count + '0';
                DisplayBoard(show, ROW, COL);
                win++;
            }
        }

        else
        {
            printf("坐标非法，重新输ru\n");            //非法位置的处理
        }
    }

    if (win == row * col - EASY_COUNT)
    {
        printf("恭喜你，排雷成功\n");                      //当win等于于非0坐标个数时游戏结束
        DisplayBoard(mine, ROW, COL);
    }

}